<template>
    <div class="desgin">
        <div class="button__wrapper">
            <div class="button" @click="handleSave">
                保存
            </div>
        </div>
        <div style="height: 400px">
            <div class="canvas" id="canvasDom">
            </div>
        </div>
        <div class="tool">
            <div class="undo-box">
                <van-icon name="revoke" @click="handleReset('left')"/>
                <van-icon class="right" @click="handleReset('right')" name="revoke" />
            </div>
            <div class="func-box">
                <div
                    v-for="item in funcList"
                    :key="item.id"
                    :class="['func-item', item.id === currentActiveFunc ? 'active' : '']"
                    @click="handleChangeFunc(item)">
                    <img :src="item.id === currentActiveFunc ? item.select_img : item.img" alt="">
                    <p>{{ item.mame }}</p>
                </div>
            </div>
        </div>
        <!-- 素材 -->
        <van-popup overlay-class="overlay-class" v-model="show2" position="bottom" :style="{ height: '45%' }" >
            <div class="popup popup2">
                <div class="header">
                    <van-tabs v-model="tabActiveName2" @click="handleChangeSucaiTab">
                        <van-tab v-for="item in tabsList2" :key="item.id" :name="item.id" :title="item.name"></van-tab>
                    </van-tabs>
                </div>
                <div class="content">
                    <van-list
                        v-model="loading2"
                        :finished="finished2"
                        finished-text="没有更多了"
                        @load="onLoad2"
                    >
                        <div class="data2-list">
                            <div style="width: 20%;padding: 5px"
                                 v-for="item in dataList2" :key="item.id"
                                @click="handleAddSucai(item)">
                                <van-image
                                    width="100%"
                                    height="100%"
                                    :src="item.imgUrl"
                                />
                            </div>
                        </div>
                    </van-list>
                </div>
            </div>
        </van-popup>
        <!-- 文本配置 -->
        <van-popup overlay-class="overlay-class" v-model="show3" position="bottom" :style="{ height: '250px' }" >
            <div class="popup popup3">
                <div class="header">
                    <span>输入样式</span>
<!--                    <van-icon name="success" @click="handleConfirm3"/>-->
                </div>
                <div class="header2">
                    <van-tabs
                        @click="handleChangeFont"
                        background="#F6F6F6"
                        title-active-color="#00C65A"
                        title-inactive-color="#303030"
                        v-model="tabActiveName33"
                        v-show="currentActiveFunc3 === '3'">
                        <van-tab v-for="item in tabsList33" :key="item.id" :name="item.id" :title="item.name"></van-tab>
                    </van-tabs>
                    <van-slider
                        v-show="currentActiveFunc3 === '6'"
                        v-model="textNode.font.fontSize" active-color="#00C65A" @change="handleChangeFOntSisze">
                    </van-slider>
                    <van-tabs
                        @click="handleChangeFontColor"
                        background="#F6F6F6"
                        title-active-color="#00C65A"
                        title-inactive-color="#303030"
                        v-model="tabActiveName34" v-show="currentActiveFunc3 === '4'">
                        <van-tab v-for="item in tabsList34" :key="item.id" :name="item.id" :title="item.name">
                            <template #title>
                                <div class="color-icon-box">
                                    <span class="color-icon" :style="{ background: item.name }"></span>
                                </div>
                            </template>
                        </van-tab>
                    </van-tabs>

                </div>
                <div class="content">
                    <div class="tool">
                        <div class="func-box">
                            <div
                                v-for="item in funcList3"
                                :key="item.id"
                                :class="['func-item', item.id === currentActiveFunc3 ? 'active' : '']"
                                @click="handleChangeFunc3(item)">
                                <img :src="item.id === currentActiveFunc3 ? item.select_img : item.img" alt="">
                                <p>{{ item.mame }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </van-popup>
        <!-- 输入文字文本 -->
        <van-popup overlay-class="overlay-class" v-model="show4" position="bottom"  >
            <div class="popup popup4">
                <div class="header">
                    <div class="button" @click="handleConfirmText">
                        完成
                    </div>
                </div>
                <div class="field-content">
                    <van-field  autosize type="textarea" ref="field" v-model="textNode.text" :input-align="inputAlign" label="" placeholder="" />
                </div>
                <div class="field-direction">
                    <van-image
                        @click="handleChangeInputAlign('left')"
                        width="24px"
                        height="24px"
                        src=""
                        :src="inputAlign === 'left' ? imageBox.leftActive : imageBox.left"
                    />
                    <van-image
                        @click="handleChangeInputAlign('center')"
                        width="24px"
                        height="24px"
                        src=""
                        :src="inputAlign === 'center' ? imageBox.centerActive : imageBox.center"
                    />
                    <van-image
                        @click="handleChangeInputAlign('right')"
                        width="24px"
                        height="24px"
                        src=""
                        :src="inputAlign === 'right' ? imageBox.rightActive : imageBox.right"
                    />
                </div>
            </div>
        </van-popup>
    </div>
</template>

<script>
// 配置项
import mixins from "@/views/mixin";
import {Topology} from '@/canvas/@topology/core'

import axios from 'axios'
import {Toast} from 'vant'

import left from '@/assets/left.png'
import leftActive from '@/assets/left_active.png'

import center from '@/assets/center.png'
import centerActive from '@/assets/center_active.png'

import right from '@/assets/right.png'
import rightActive from '@/assets/right_active.png'

const canvasOptions = {
    lineName: 'line',
    minScale: 0,
    maxScale: 50,
    // 连线颜色
    color: '#fff',
    font: {
        color: '#fff',
        fontSize: 12,
        textBaseline: 'bottom'
    },
    // 键盘事件 如 删除 移动
    keydown: -1,
    // 缩放 如 ctrl + mousewheel 缩放
    disableScale: true,
    // 移动 如 ctrl + mouse 移动
    disableTranslate: false,
    disableEmptyLine: false,
    autoAnchor: false,
    autoExpandDistance: 0,
    cacheLen: 10000,
    hideAnchor: true // 隐藏锚点
}

export default {
    name: "createdesgin",
  mixins: [mixins],
  data() {
        return {
            /**
             *  路由传参数
             */
            templateCardId: null,
            templateCardImageUrl: '',
            title: '',
            /**
             *
             */
            canvas: null,
            currentActiveFunc: '1',
            // 素材
            show2: false,
            tabActiveName2: 1,
            tabsList2: [
                {
                    id: 1,
                    name: '收藏'
                },
                {
                    id: 2,
                    name: 'emoji'
                },
                {
                    id: 3,
                    name: '热门'
                },
                {
                    id: 4,
                    name: '搞笑'
                },
            ],
            sucaiItem: null,
            loading2: false,
            finished2: false,
            pageNo2: 1,
            pageSize2: 20,
            total2: 0,
            dataList2: [
            ],
            // 文本
            show3: false,
            currentActiveFunc3: '',
            // 字体
            tabActiveName33: '',
            tabsList33: [
                {
                    id: 'Test2',
                    name: '微软雅黑'
                },
                {
                    id: 'Test',
                    name: '艺术字'
                },
            ],
            // 颜色
            tabActiveName34: '',
            tabsList34: [
                {
                    id: 1,
                    name: '#FF1F1F'
                },
                {
                    id: 2,
                    name: '#FFB11F'
                },
                {
                    id: 3,
                    name: '#FFE71F'
                },
                {
                    id: 4,
                    name: '#1FFF2C'
                },
                {
                    id: 5,
                    name: '#1F6DFF'
                },
                {
                    id: 6,
                    name: '#471FFF'
                },
                {
                    id: 7,
                    name: '#FF1FBF'
                },
                {
                    id: 8,
                    name: '#000000'
                }
            ],
            /**
             *  当前文本的事件
             */
            textNodeEvent: '',
            textNode: {
                text: '',
                font: {
                    fontSize: 12
                }
            },
            inputAlign: 'center',
            imageBox: {
                left,
                leftActive,
                center,
                centerActive,
                right,
                rightActive
            },
            // 输入文本
            show4: false,
          cardDetail: {}
        }
    },
    mounted() {
        this.initRouteQuery()
      this.getSucaiType()
    },
    methods: {
      /**
       *  初始化路由参数
       */
      initRouteQuery() {
          Toast.loading({
              message: '',
              duration: 0
          })
        const { token, id } = this.$route.query
        localStorage.setItem('token', token || '')
        this.cardId = id
        axios({
          method: 'GET',
          url: this.baseUrl +`/api/v1/card/detail/${id}`,
          headers: {
            'X-UNI-TOKEN': localStorage.getItem('token'),
          },
        }).then(res => {
          this.cardDetail = res.data.data
          this.initCanvas()
          Toast.clear()
        })
      },
      /**
       *  保存
       */
      handleSave() {
            this.handleSaveImage().then(res => {
                setTimeout(() => {
                    wx.miniProgram.navigateBack()
                },1000)
            })
      },
      async handleSaveImage() {
          return new Promise(async (resolve,reject) => {
              const imageUrl = await this.uploadImage()
              axios({
                  method: 'POST',
                  url: this.baseUrl + '/api/v1/card/edit',
                  headers: {
                      'X-UNI-TOKEN': localStorage.getItem('token'),
                  },
                  data: {
                      "cardId": this.cardDetail.cardId,
                      "configure": JSON.stringify(this.canvas.data),
                      "imgUrl": imageUrl,
                      "title": this.cardDetail.title
                  }
              }).then(res => {
                  if (res.data.code === 200) {
                      Toast.success('保存成功')
                      resolve()
                  } else {
                      reject()
                      Toast.fail(res.data.msg)
                  }
              }).catch((err) => {
                  Toast.fail(err || '请求出错')
              })
          })
      },
        /**
         *  初始化画布
         */
        initCanvas() {
            this.canvas = null
            canvasOptions.on = this.onMessage
            this.canvas = new Topology('canvasDom', canvasOptions)
            setTimeout(() => {
                this.canvas.open(this.cardDetail.configure || {})
                this.canvas.render()
                if (location.href.split("&UPLOAD_FILE=")[1]) {
                    console.log('decodeURIComponent(location.href.split("&UPLOAD_FILE=")[1])',decodeURIComponent(location.href.split("&UPLOAD_FILE=")[1]))
                    this.canvas.addNode({
                        rect: {
                            x: 170,
                            y: 75,
                            width: 50,
                            height: 50
                        },
                        image: decodeURIComponent(location.href.split("&UPLOAD_FILE=")[1]),
                        name: 'image'
                    },true)
                    this.canvas.render()
                }
            },0)
        },
        onMessage(event, data) {
            if (data && data.id) {
                this.textNode = data
            } else {
                this.textNode = {
                    text: '',
                    font: {
                        fontSize: 12
                    }
                }
            }
            // 右侧输入框编辑状态时点击编辑区域其他元素，onMessage执行后才执行onUpdateProps方法，通过setTimeout让onUpdateProps先执行
            setTimeout(() => {
                switch (event) {
                    case 'addNode':
                        data.hideInput = true
                        break
                    case 'node':
                        console.log('node')
                        if (data.name === 'text') {
                            this.textNodeEvent = 'node'
                            setTimeout(() => {
                                console.log('this.textNodeEvent',this.textNodeEvent)
                                if (this.textNodeEvent === 'node') {
                                    // 文本
                                    this.currentActiveFunc = '4'
                                    this.show3 = true
                                }
                            },300)
                        }
                        break
                    case 'move':
                        if (data.some(el => el.name === 'text')) {
                            this.textNodeEvent = 'move'
                        }
                        break
                }
            }, 0)
        },
      /**
       *  初始工具栏
       * @param item
       */
       async handleChangeFunc(item) {
            this.currentActiveFunc = item.id
            switch (item.id) {
                case '1':
                    if (!this.textNode.id) {
                        Toast('未选中需要清除的素材')
                        return
                    }
                    this.canvas.data.pens.forEach((pen,index) => {
                        if (pen.id === this.textNode.id) {
                            this.canvas.data.pens.splice(index,1)
                        }
                    })
                    this.canvas.render()
                    break
                case '2':
                    // 打开素材
                    this.show2 = true
                    break
              // 照片上传
                case '3':
                    this.handleSaveImage().then(cardId => {
                        wx.miniProgram.postMessage({
                            data: {
                                action: 'image',
                                cardId: cardId
                            }
                        })
                        wx.miniProgram.redirectTo({
                            url: `/pages/desgin/edit?id=${cardId}`
                        })
                    })
                    break
              // 新增文本节点
                case '4':
                    this.textNode = {
                        text: '',
                        font: {
                            fontSize: 14,
                            textAlign: 'center'
                        }
                    }
                    this.inputAlign = 'center'
                    this.show4 = true
                    this.$nextTick(() => {
                        this.$refs.field.focus()
                    })
                    break
                // 前面
                case '5':
                    if (this.textNode.id) {
                        this.canvas.top(this.textNode)
                        this.canvas.render()
                    }
                    break
                case '6':
                    if (this.textNode.id) {
                        this.canvas.bottom(this.textNode)
                        this.canvas.render()
                    }
                    break
            }
        },
        /**
         *  素材相关
         */
        // 根据素材类别id 查询素材列表
        handleChangeSucaiTab(id) {
          this.getSucaiList(id)
        },
        // 选中素材
        handleAddSucai(item) {
          this.canvas.addNode({
            rect: {
                x: 170,
                y: 75,
              width: 50,
              height: 50
            },
            image: item.imgUrl,
            name: 'image'
          },true)
          this.canvas.render()
        },
        // 确认选择素材
        handleConfirm2() {
            this.show2 = false
        },
        onLoad2() {
            // 加载状态结束
            this.loading2 = false;
            // 数据全部加载完成
            if (this.dataList2.length >= this.total2) {
                this.finished2 = true;
            }
        },
        /**
         *  文本相关
         */
        handleChangeInputAlign(value) {
            this.inputAlign = value
            this.textNode.font.textAlign = value
            this.canvas.render()
            this.$nextTick(() => {
                this.$refs.field.focus()
            })
        },
        // 文本编辑确认
        handleConfirmText() {
          // 编辑
          if (this.textNode.id) {
            this.show3 = false
          } else {
            // 新增
            this.canvas.addNode({
              text: this.textNode.text,
              rect: {
                  x: 140,
                  y: 75,
                width: 100,
                height: 50
              },
              font: {
                color: '#000'
              },
              name: 'text'
            },true)
          }
          this.canvas.render()
          this.show4 = false
        },
        // 确认文本字体 颜色等配置
        handleChangeFont(value,name) {
          console.log(value,name)
          console.log(this.textNode)
          this.textNode.font.fontFamily = value
          this.canvas.render()
        },
        handleChangeFontColor(value,name) {
          console.log(value,name)
          this.textNode.font.color = name
          this.canvas.render()
        },
        handleChangeFOntSisze(value) {
            this.canvas.render()
        },
        // 文本菜单选中
        handleChangeFunc3(item) {
            this.currentActiveFunc3 = item.id
            switch (item.id) {
              // 删除文字节点
                case '1':
                  this.canvas.data.pens.forEach((pen,index) => {
                    if (pen.id === this.textNode.id) {
                      this.canvas.data.pens.splice(index,1)
                    }
                  })
                    this.canvas.render()
                    this.show3 = false
                    break
              // 编辑文字
                case '2':
                  this.show4 = true
                    break
                case '3':
                    break
                case '4':
                    break;

            }
        },
    }
}
</script>

<style lang="less">
@import "~@/style/index.css";
@import "~@/style/desgin.less";
</style>
